const { Service } = require('egg')
const { MD5 } = require('../utils/encryption')
// const { v4: uuidv4 } = require('uuid');

module.exports = class LoginService extends Service {
  /**
   * * 模拟登录，获取cookie
   * @return {setCookie: string, status: number} **
   */
  async getCookie() {
    try {
      const { ctx } = this
      const { sid, pwd } = ctx.data
      // 1.请求门户网站
      const apiUrl = 'https://sso.hnuit.edu.cn/cas/login?service=http%3A%2F%2Fjwgl.hnisc.com%2Fjsxsd%2F'
      const res = await ctx.curl(apiUrl, {
        method: 'GET',
        headers: {
          'Accept-Encoding': 'gzip, deflate, br, zstd',
          'Accept-Language': 'zh-CN,zh;q=0.9',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
        },
      })
      const execution = /name="execution" value="(.*?)"/.exec(res.data.toString())[1]
      const password = MD5(pwd)

      // 2.请求获取time的js文件，请求cookie2
      const apiUrl1 = 'https://sso.hnuit.edu.cn/cas/getCode?code=0'
      const res1 = await ctx.curl(apiUrl1, {
        method: 'GET',
        headers: {
          'Content-Type': 'text/html;charset=UTF-8',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
        },
      })
      const timeJson = JSON.parse(res1.data.toString())
      const timedata = timeJson.data
      const time = Object.keys(timedata)[0]
      const setCookieArray2 = res1.headers['set-cookie'] ? res1.headers['set-cookie'].map((e) => e.split(';')[0]) : ''
      const setCookie1 = setCookieArray2
      console.log('setCookie', setCookie1)

      // 3.请求cookie3
      const cookieUrl = 'https://sso.hnuit.edu.cn/cas/getUrl'
      const resCookie = await ctx.curl(cookieUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
        },
        data: {
          url: 'https://sso.hnuit.edu.cn/cas/login?service=http%3A%2F%2Fjwgl.hnisc.com%2Fjsxsd%2F',
        },
      })
      const setCookieArray3 = resCookie.headers['set-cookie'] ? resCookie.headers['set-cookie'].map((e) => e.split(';')[0]) : ''
      let setCookie = `${setCookieArray3[0]};${setCookie1};${setCookieArray3[1]}`

      // 4.请求登录页面
      const apiUrl2 = 'https://sso.hnuit.edu.cn/cas/login?service=http%3A%2F%2Fjwgl.hnisc.com%2Fjsxsd%2F'
      const res2 = await ctx.curl(apiUrl2, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          Cookie: setCookie,
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
        },
        data: {
          execution,
          _eventId: 'submit',
          geolocation: '',
          authType: '1',
          username: sid,
          time,
          password,
          captcha: '',
        },
      })
      console.log('res2.headers.location', res2.headers.location)
      // 5.重定向1
      const RedirectRes1 = await ctx.curl(res2.headers.location, {
        method: 'GET',
        headers: {
          Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,'
          + 'image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
          'Upgrade-Insecure-Requests': '1',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
        },
      })
      const setCookieArray4 = RedirectRes1.headers['set-cookie'] ? RedirectRes1.headers['set-cookie'].map((e) => e.split(';')[0]) : ''
      console.log('setCookieArray4', setCookieArray4)
      setCookie = `${setCookieArray4[0]};${setCookieArray4[1]}`
      console.log('setCookie', setCookie)
      // 6.重定向2
      const RedirectRes2 = await ctx.curl(RedirectRes1.headers.location, {
        method: 'GET',
        headers: {
          'Accept-Encoding': 'gzip, deflate, br, zstd',
          'Accept-Language': 'zh-CN,zh;q=0.9',
          Cookie: setCookie,
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
        },
      })
      return { setCookie, status: RedirectRes2.status }
    } catch (err) {
      console.log(err)
      return { setCookie: '', status: 500 }
    }
  }
}
